import { getOssSign } from "@/utils/dataUtil";
import axios from "axios";
import { useEffect, useState } from "react";

//oss服务器签名，前端直传
const useOssHooks = () => {

    //oss
    const [ossData, setOssData] = useState();

    /**
     * 自定义oss上传请求
     * @param uploadOption 参数
     */
    const customOssRequest = async (file) => {
        const formData = new FormData();
        formData.append("key", (ossData?.dir + "/" + file.name));
        formData.append("success_action_status", "200");
        formData.append("OSSAccessKeyId", ossData?.OSSAccessKeyId + "");
        formData.append("Signature", ossData?.Signature + "");
        formData.append("policy", ossData?.policy + "");
        formData.append("Expires", ossData?.Expires + "");
        formData.append("file", file);
        const config = {
            withCredentials: false,
            headers: {
                "content-type": "multipart/form-data"
            },
        };
        try {
            const res = await axios.post(
                ossData.host,
                formData,
                config
            );
            if(res.status === 200) {
                return {
                    url: res.config.url + "/" + res.config.data.get("key")
                }
            }
        } catch (err) {
            throw new Error('上传失败，请稍后再试')
        }
    }

    /** 获取服务器oss签名参数 */
    useEffect(() => {
        getOssSign().then(res => {
            if (res.status === 1) {
                const { accessKeyId, dir, expires, host, policy, signature } = res.data;
                setOssData({
                    "OSSAccessKeyId": accessKeyId,
                    "Signature": signature,
                    "dir": dir,
                    "Expires": expires,
                    "host": host,
                    "policy": policy,
                });
            }
        });
    }, []);

    return {
        customOssRequest
    };
}

export {
    useOssHooks
}